package com.zhentao.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhentao.pojo.User;
import com.zhentao.websocket.pojo.ChatMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 聊天消息数据迁移服务
 * 用于处理现有数据，添加conversationId字段
 */
@Service
public class ChatMessageMigrationService {

    private static final Logger log = LoggerFactory.getLogger(ChatMessageMigrationService.class);

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private UserService userService;

    /**
     * 迁移现有消息数据，添加conversationId字段
     */
    public void migrateExistingMessages() {
        try {
            log.info("开始迁移聊天消息数据...");
            
            // 查询所有没有conversationId的消息
            Query query = new Query();
            Criteria criteria = new Criteria().orOperator(
                Criteria.where("conversationId").exists(false),
                Criteria.where("conversationId").isNull(),
                Criteria.where("conversationId").is("")
            );
            query.addCriteria(criteria);
            
            List<ChatMessage> messages = mongoTemplate.find(query, ChatMessage.class);
            log.info("找到需要迁移的消息数量: {}", messages.size());
            
            int migratedCount = 0;
            int batchSize = 100;
            
            for (int i = 0; i < messages.size(); i += batchSize) {
                int end = Math.min(i + batchSize, messages.size());
                List<ChatMessage> batch = messages.subList(i, end);
                
                for (ChatMessage message : batch) {
                    try {
                        // 生成conversationId
                        String conversationId = generateConversationId(message.getFromName(), message.getToName());
                        
                        // 更新单条消息
                        Query updateQuery = new Query(Criteria.where("id").is(message.getId()));
                        Update update = new Update().set("conversationId", conversationId);
                        
                        mongoTemplate.updateFirst(updateQuery, update, ChatMessage.class);
                        migratedCount++;
                        
                        if (migratedCount % 50 == 0) {
                            log.debug("已迁移消息数量: {}", migratedCount);
                        }
                        
                    } catch (Exception e) {
                        log.error("迁移消息失败，消息ID: {}", message.getId(), e);
                    }
                }
            }
            
            log.info("聊天消息数据迁移完成，成功迁移: {} 条消息", migratedCount);
            
        } catch (Exception e) {
            log.error("聊天消息数据迁移失败", e);
            throw new RuntimeException("聊天消息数据迁移失败: " + e.getMessage(), e);
        }
    }

    /**
     * 验证迁移结果
     */
    public MigrationResult validateMigration() {
        try {
            // 统计总消息数
            long totalMessages = mongoTemplate.count(new Query(), ChatMessage.class);
            
            // 统计有conversationId的消息数
            Query withConversationIdQuery = new Query();
            withConversationIdQuery.addCriteria(
                Criteria.where("conversationId").exists(true)
                    .and("conversationId").ne(null)
                    .and("conversationId").ne("")
            );
            long withConversationId = mongoTemplate.count(withConversationIdQuery, ChatMessage.class);
            
            // 统计没有conversationId的消息数
            Query withoutConversationIdQuery = new Query();
            withoutConversationIdQuery.addCriteria(
                new Criteria().orOperator(
                    Criteria.where("conversationId").exists(false),
                    Criteria.where("conversationId").isNull(),
                    Criteria.where("conversationId").is("")
                )
            );
            long withoutConversationId = mongoTemplate.count(withoutConversationIdQuery, ChatMessage.class);
            
            MigrationResult result = new MigrationResult();
            result.setTotalMessages(totalMessages);
            result.setWithConversationId(withConversationId);
            result.setWithoutConversationId(withoutConversationId);
            result.setMigrationComplete(withoutConversationId == 0);
            
            log.info("迁移验证结果: {}", result);
            return result;
            
        } catch (Exception e) {
            log.error("验证迁移结果失败", e);
            throw new RuntimeException("验证迁移结果失败: " + e.getMessage(), e);
        }
    }

    /**
     * 生成会话ID（两个用户之间的唯一标识）
     */
    private String generateConversationId(String user1, String user2) {
        if (user1 == null || user2 == null) {
            throw new IllegalArgumentException("用户名不能为空");
        }
        
        // 按字典序排列，确保同一对用户生成相同的会话ID
        String[] users = {user1.trim(), user2.trim()};
        Arrays.sort(users);
        return users[0] + "_" + users[1];
    }

    /**
     * 迁移结果统计类
     */
    public static class MigrationResult {
        private long totalMessages;
        private long withConversationId;
        private long withoutConversationId;
        private boolean migrationComplete;

        // Getters and Setters
        public long getTotalMessages() {
            return totalMessages;
        }

        public void setTotalMessages(long totalMessages) {
            this.totalMessages = totalMessages;
        }

        public long getWithConversationId() {
            return withConversationId;
        }

        public void setWithConversationId(long withConversationId) {
            this.withConversationId = withConversationId;
        }

        public long getWithoutConversationId() {
            return withoutConversationId;
        }

        public void setWithoutConversationId(long withoutConversationId) {
            this.withoutConversationId = withoutConversationId;
        }

        public boolean isMigrationComplete() {
            return migrationComplete;
        }

        public void setMigrationComplete(boolean migrationComplete) {
            this.migrationComplete = migrationComplete;
        }

        @Override
        public String toString() {
            return "MigrationResult{" +
                    "totalMessages=" + totalMessages +
                    ", withConversationId=" + withConversationId +
                    ", withoutConversationId=" + withoutConversationId +
                    ", migrationComplete=" + migrationComplete +
                    '}';
        }
    }

    /**
     * 为所有现有聊天消息添加头像信息
     */
    public void migrateAvatarsForAllMessages() {
        log.info("开始为所有聊天消息添加头像信息...");

        try {
            // 查询所有没有头像信息的消息
            Query query = new Query();
            query.addCriteria(Criteria.where("fromAvatar").exists(false));

            List<ChatMessage> messages = mongoTemplate.find(query, ChatMessage.class);
            log.info("找到 {} 条需要更新头像的消息", messages.size());

            if (messages.isEmpty()) {
                log.info("没有需要更新的消息");
                return;
            }

            // 缓存用户头像信息，避免重复查询
            Map<String, String> userAvatarCache = new HashMap<>();

            int updateCount = 0;
            int batchSize = 100;

            for (int i = 0; i < messages.size(); i++) {
                ChatMessage message = messages.get(i);

                try {
                    // 获取发送方头像
                    String fromAvatar = getUserAvatarFromCache(message.getFromName(), userAvatarCache);

                    // 获取接收方头像
                    String toAvatar = getUserAvatarFromCache(message.getToName(), userAvatarCache);

                    // 更新消息
                    Query updateQuery = new Query(Criteria.where("id").is(message.getId()));
                    Update update = new Update();

                    if (fromAvatar != null) {
                        update.set("fromAvatar", fromAvatar);
                    }

                    if (toAvatar != null) {
                        update.set("toAvatar", toAvatar);
                    }

                    if (update.getUpdateObject().size() > 0) {
                        mongoTemplate.updateFirst(updateQuery, update, ChatMessage.class);
                        updateCount++;
                    }

                    // 批量处理进度日志
                    if ((i + 1) % batchSize == 0) {
                        log.info("已处理 {}/{} 条消息", i + 1, messages.size());
                    }

                } catch (Exception e) {
                    log.warn("更新消息 {} 的头像信息失败: {}", message.getId(), e.getMessage());
                }
            }

            log.info("头像信息迁移完成，共更新 {} 条消息", updateCount);

        } catch (Exception e) {
            log.error("头像信息迁移失败", e);
            throw new RuntimeException("头像信息迁移失败: " + e.getMessage(), e);
        }
    }

    /**
     * 从缓存中获取用户头像，如果缓存中没有则查询数据库
     */
    private String getUserAvatarFromCache(String username, Map<String, String> cache) {
        if (!StringUtils.hasText(username)) {
            return null;
        }

        // 检查缓存
        if (cache.containsKey(username)) {
            return cache.get(username);
        }

        // 查询数据库
        String avatar = getUserAvatar(username);
        cache.put(username, avatar); // 缓存结果（包括null）

        return avatar;
    }

    /**
     * 根据用户名获取用户头像
     */
    private String getUserAvatar(String username) {
        try {
            User user = userService.getOne(new QueryWrapper<User>()
                    .eq("username", username)
                    .eq("status", 1)); // 只查询正常状态的用户

            if (user != null && StringUtils.hasText(user.getAvatar())
                && !"identity_verified".equals(user.getAvatar())) {
                return user.getAvatar();
            }

            return null;
        } catch (Exception e) {
            log.warn("查询用户 {} 头像失败: {}", username, e.getMessage());
            return null;
        }
    }

    /**
     * 获取头像迁移统计信息
     */
    public Map<String, Object> getAvatarMigrationStats() {
        Map<String, Object> stats = new HashMap<>();

        try {
            // 总消息数
            long totalMessages = mongoTemplate.count(new Query(), ChatMessage.class);
            stats.put("totalMessages", totalMessages);

            // 有头像信息的消息数
            Query hasAvatarQuery = new Query();
            hasAvatarQuery.addCriteria(Criteria.where("fromAvatar").exists(true));
            long messagesWithAvatar = mongoTemplate.count(hasAvatarQuery, ChatMessage.class);
            stats.put("messagesWithAvatar", messagesWithAvatar);

            // 需要迁移的消息数
            long needMigration = totalMessages - messagesWithAvatar;
            stats.put("needMigration", needMigration);

            // 迁移完成率
            double completionRate = totalMessages > 0 ? (double) messagesWithAvatar / totalMessages * 100 : 0;
            stats.put("completionRate", Math.round(completionRate * 100.0) / 100.0);

        } catch (Exception e) {
            log.error("获取头像迁移统计信息失败", e);
            stats.put("error", e.getMessage());
        }

        return stats;
    }
}